from sqlalchemy import Column, Integer, Date, JSON
from database import Base
from sqlalchemy.orm import relationship
from sqlalchemy import ForeignKey
from datetime import date

class Consultation(Base):
    __tablename__ = "consultation"

    ID = Column(Integer, primary_key=True, index=True, autoincrement=True)
    doctor_ID = Column(Integer, ForeignKey("doctor.ID"))
    patient_ID = Column(Integer, ForeignKey("patient.ID"))
    con_date = Column(Date, default=date.today())
    result = Column(JSON)

    # 定义关系###关系在数据库中建立了关联，能让ORM自动处理表之间的连接（双向导航貌似建立了一种类似外键的联系？）
    doctor = relationship("Doctor", back_populates="consultations")
    patient = relationship("Patient", back_populates="consultations")

    def to_dict(self):
        return {
            "ID": self.ID,
            "doctor_ID": self.doctor_ID,
            "patient_ID": self.patient_ID,
            "con_date": self.con_date.isoformat() if self.con_date else None,
            "result": self.result
        }

    @classmethod
    def from_dict(cls, data: dict) -> "Consultation":
        valid_keys = set(cls.__table__.columns.keys())
        return cls(**{k: v for k, v in data.items() if k in valid_keys})